import json
import random
from typing import Any, Dict, List, Optional, Tuple

import re
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer

# 尝试下载NLTK资源，如果尚未下载
try:
    nltk.data.find('tokenizers/punkt')
except LookupError:
    nltk.download('punkt')
try:
    nltk.data.find('sentiment/vader_lexicon.zip')
except LookupError:
    nltk.download('vader_lexicon')

from app.core.logging import logger


class VirtualNLPModel:
    """虚拟NLP模型，用于模拟真实NLP功能"""
    
    def __init__(self):
        """初始化虚拟NLP模型"""
        logger.info("Initializing Virtual NLP Model")
        self.sia = SentimentIntensityAnalyzer()
        
        # 加载PUA模式示例
        self.pua_patterns = self._load_pua_patterns()
    
    def _load_pua_patterns(self) -> List[Dict[str, Any]]:
        """加载PUA模式示例"""
        # 这里应该从文件或数据库中加载，但现在我们使用硬编码的方式
        patterns = [
            {
                "pattern": r"你太敏感了|你想太多了|我没那个意思",
                "category": "gaslighting",
                "severity": 0.7,
                "description": "煤气灯效应，让对方怀疑自己的感受和判断"
            },
            {
                "pattern": r"我从没见过像你这么[好美聪明]的人|你是我遇到的最[好美聪明]的人",
                "category": "love_bombing",
                "severity": 0.5,
                "description": "爱情轰炸，过度赞美以快速建立亲密感"
            },
            {
                "pattern": r"你这样的人一般都[找不到对象|嫁不出去]|对于你的条件来说已经不错了",
                "category": "negging",
                "severity": 0.8,
                "description": "负面评价，通过批评降低对方自尊心"
            },
            {
                "pattern": r"你的朋友对你没好处|他们在利用你|你只要有我就够了",
                "category": "isolation",
                "severity": 0.9,
                "description": "隔离控制，试图切断对方与他人的联系"
            },
            {
                "pattern": r"我前任可不是这样的|有很多人想和我[在一起|约会]",
                "category": "triangulation",
                "severity": 0.6,
                "description": "三角关系，引入第三者制造不安全感"
            }
        ]
        return patterns
    
    async def analyze_emotion(self, text: str) -> Dict[str, float]:
        """
        分析文本的情感
        """
        # 使用NLTK的SentimentIntensityAnalyzer
        scores = self.sia.polarity_scores(text)
        
        # 调整输出格式
        result = {
            "positive": scores["pos"],
            "negative": scores["neg"],
            "neutral": scores["neu"],
            "dominant_emotion": "neutral"
        }
        
        # 确定主导情绪
        if scores["pos"] > scores["neg"] and scores["pos"] > scores["neu"]:
            result["dominant_emotion"] = "positive"
        elif scores["neg"] > scores["pos"] and scores["neg"] > scores["neu"]:
            result["dominant_emotion"] = "negative"
        
        return result
    
    async def analyze_tone(self, text: str) -> Dict[str, Any]:
        """
        分析文本的语气
        """
        # 简单规则模拟语气分析
        formal_patterns = [
            r"尊敬|敬爱|请问|谢谢|致歉|感谢|恳请",
            r"希望|可否|建议|请求",
            r"先生|小姐|女士|先生",
            r"如果.*可以|是否可以"
        ]
        formal_score = self._pattern_match_score(text, formal_patterns)
        
        friendly_patterns = [
            r"哈哈|嘻嘻|呵呵|😄|😊|👍|❤️",
            r"亲爱的|亲|宝贝|哥们|兄弟|姐妹",
            r"谢谢你|感谢你|么么哒",
            r"开心|高兴|快乐|玩得"
        ]
        friendly_score = self._pattern_match_score(text, friendly_patterns)
        
        aggressive_patterns = [
            r"你怎么|你凭什么|你必须|我要求你",
            r"难道|居然|竟然|简直",
            r"!{2,}|\?{2,}|！{2,}|？{2,}",
            r"废话|放屁|胡说|扯淡"
        ]
        aggressive_score = self._pattern_match_score(text, aggressive_patterns)
        
        submissive_patterns = [
            r"打扰了|麻烦你了|不好意思|抱歉|对不起",
            r"如果可以的话|如果方便的话|可能的话",
            r"请多多|请多指教|请多关照",
            r"我想请问|我想知道|希望得到"
        ]
        submissive_score = self._pattern_match_score(text, submissive_patterns)
        
        confident_patterns = [
            r"当然|肯定|一定|必然|确实",
            r"我认为|我相信|我敢说",
            r"毫无疑问|显然|明显",
            r"我很确定|我很肯定"
        ]
        confident_score = self._pattern_match_score(text, confident_patterns)
        
        # 确定主导语气
        tone_scores = {
            "formal": formal_score,
            "friendly": friendly_score,
            "aggressive": aggressive_score,
            "submissive": submissive_score,
            "confident": confident_score
        }
        dominant_tone = max(tone_scores, key=tone_scores.get)
        
        return {
            "formal": formal_score,
            "friendly": friendly_score,
            "aggressive": aggressive_score,
            "submissive": submissive_score,
            "confident": confident_score,
            "dominant_tone": dominant_tone
        }
    
    def _pattern_match_score(self, text: str, patterns: List[str]) -> float:
        """
        根据模式匹配计算分数
        """
        score = 0.0
        for pattern in patterns:
            if re.search(pattern, text, re.IGNORECASE):
                score += 0.25  # 每匹配一个模式增加0.25分
        
        return min(score, 1.0)  # 最高分为1.0
    
    async def analyze_topic(self, text: str) -> Dict[str, Any]:
        """
        分析文本的主题
        """
        # 简单实现，基于关键词的主题识别
        topics = {
            "工作": ["工作", "项目", "会议", "报告", "任务", "客户", "公司", "业务", "职场", "面试"],
            "学习": ["学习", "考试", "课程", "作业", "论文", "研究", "知识", "教育", "学校", "大学"],
            "情感": ["爱情", "喜欢", "爱", "感情", "暗恋", "分手", "结婚", "恋爱", "表白", "心动"],
            "日常": ["日常", "生活", "吃饭", "睡觉", "休息", "逛街", "购物", "电影", "旅游", "天气"],
            "社交": ["聚会", "朋友", "聊天", "交友", "社交", "活动", "见面", "约会", "认识", "联系"]
        }
        
        topic_scores = {}
        for topic, keywords in topics.items():
            score = 0
            for keyword in keywords:
                if keyword in text:
                    score += 1
            topic_scores[topic] = min(score / len(keywords), 1.0)
        
        # 找出得分最高的主题
        main_topic = max(topic_scores, key=topic_scores.get)
        
        # 格式化为列表
        topic_list = [{"topic": k, "score": v} for k, v in topic_scores.items()]
        
        return {
            "topics": topic_list,
            "main_topic": main_topic
        }
    
    async def detect_pua(self, text: str) -> Dict[str, Any]:
        """
        检测PUA话术
        """
        detected_patterns = []
        total_score = 0.0
        
        for pattern_info in self.pua_patterns:
            pattern = pattern_info["pattern"]
            if re.search(pattern, text, re.IGNORECASE):
                severity = pattern_info["severity"]
                detected_patterns.append({
                    "category": pattern_info["category"],
                    "description": pattern_info["description"],
                    "severity": severity,
                    "matched_text": re.search(pattern, text, re.IGNORECASE).group()
                })
                total_score += severity
        
        # 计算总体分数
        pua_score = min(total_score / 3.0, 1.0) if detected_patterns else 0.0
        
        # 确定风险等级
        if pua_score == 0:
            risk_level = "none"
        elif pua_score < 0.3:
            risk_level = "low"
        elif pua_score < 0.7:
            risk_level = "medium"
        else:
            risk_level = "high"
        
        # 生成回复建议
        response_suggestions = []
        if detected_patterns:
            if "gaslighting" in [p["category"] for p in detected_patterns]:
                response_suggestions.append("我相信我的感受是真实的，这不是我想太多。")
            if "love_bombing" in [p["category"] for p in detected_patterns]:
                response_suggestions.append("谢谢你的赞美，不过我觉得我们应该多了解一下彼此。")
            if "negging" in [p["category"] for p in detected_patterns]:
                response_suggestions.append("你的评价听起来有点负面，我觉得相互尊重更重要。")
            if "isolation" in [p["category"] for p in detected_patterns]:
                response_suggestions.append("我珍视我的社交圈，我的朋友对我很重要。")
            if "triangulation" in [p["category"] for p in detected_patterns]:
                response_suggestions.append("我不太舒服比较我和其他人，我们应该关注我们自己的关系。")
        
        # 如果没有匹配特定类别，但检测到PUA
        if pua_score > 0 and not response_suggestions:
            response_suggestions = [
                "我需要考虑一下这个问题。",
                "让我们换个话题吧。",
                "我觉得我们应该保持一个健康的交流方式。"
            ]
        
        return {
            "is_pua": pua_score > 0.3,  # 分数超过0.3才判定为PUA
            "score": pua_score,
            "detected_patterns": detected_patterns,
            "risk_level": risk_level,
            "explanation": f"检测到{len(detected_patterns)}种PUA话术模式，总体风险为{risk_level}" if detected_patterns else "未检测到明显的PUA话术",
            "response_suggestions": response_suggestions
        }
    
    async def generate_optimization(
        self, 
        text: str, 
        relationship_type: str,
        chat_goal: str,
        context_messages: Optional[List[Dict[str, Any]]] = None
    ) -> Dict[str, Any]:
        """
        生成优化建议
        """
        # 分析原始文本
        emotion_analysis = await self.analyze_emotion(text)
        tone_analysis = await self.analyze_tone(text)
        topic_analysis = await self.analyze_topic(text)
        
        # 根据关系类型和聊天目标生成优化建议
        suggestions = []
        
        # 生成1-3条优化建议
        num_suggestions = random.randint(1, 3)
        
        for i in range(num_suggestions):
            suggestion = await self._generate_single_optimization(
                text, relationship_type, chat_goal, 
                emotion_analysis, tone_analysis, topic_analysis
            )
            suggestions.append(suggestion)
        
        # 构建完整分析结果
        chat_analysis = {
            "emotion": {
                "positive": emotion_analysis["positive"],
                "negative": emotion_analysis["negative"],
                "neutral": emotion_analysis["neutral"],
                "dominant_emotion": emotion_analysis["dominant_emotion"]
            },
            "tone": tone_analysis,
            "topic": topic_analysis,
            "word_count": len(text),
            "avg_response_time": None,
            "relationship_assessment": f"{relationship_type}关系良好" if random.random() > 0.3 else f"{relationship_type}关系需要改善",
            "goal_achievement": random.uniform(0.4, 0.9)
        }
        
        return {
            "original_text": text,
            "suggestions": suggestions,
            "analysis": chat_analysis
        }
    
    async def _generate_single_optimization(
        self, 
        text: str, 
        relationship_type: str,
        chat_goal: str,
        emotion_analysis: Dict[str, Any],
        tone_analysis: Dict[str, Any],
        topic_analysis: Dict[str, Any]
    ) -> Dict[str, Any]:
        """
        生成单条优化建议
        """
        # 根据关系类型和聊天目标调整语气
        suggested_text = text
        explanation = ""
        modification_points = []
        
        # 简单示例：如果是正式关系（上级、客户），增加礼貌用语
        if relationship_type in ["superior", "client"]:
            if random.random() > 0.5 and "谢谢" not in text and "感谢" not in text:
                suggested_text = f"{suggested_text} 谢谢您的支持。"
                modification_points.append({
                    "type": "addition",
                    "position": "end",
                    "original": "",
                    "suggested": " 谢谢您的支持。",
                    "reason": "增加礼貌用语，表示尊重"
                })
                explanation += "添加礼貌用语，增强专业性和尊重度。"
        
        # 如果是社交聊天目标，增加情感表达
        if chat_goal == "social" and tone_analysis["friendly"] < 0.5:
            if random.random() > 0.6:
                emoji_additions = ["😊", "👍", "🙂"]
                chosen_emoji = random.choice(emoji_additions)
                suggested_text = f"{suggested_text} {chosen_emoji}"
                modification_points.append({
                    "type": "addition",
                    "position": "end",
                    "original": "",
                    "suggested": f" {chosen_emoji}",
                    "reason": "增加表情符号，增强亲和力"
                })
                explanation += "添加表情符号，使语气更加友好。"
        
        # 如果是工作汇报目标，增加明确表述
        if chat_goal == "work_report" and "已完成" not in text and "正在进行" not in text:
            if random.random() > 0.7:
                suggested_text = f"关于这项工作，已完成进度约70%。{suggested_text}"
                modification_points.append({
                    "type": "addition",
                    "position": "start",
                    "original": "",
                    "suggested": "关于这项工作，已完成进度约70%。",
                    "reason": "增加明确的进度说明，使汇报更清晰"
                })
                explanation += "添加明确的工作进度表述，提高汇报清晰度。"
        
        # 如果是协商目标，增加缓和语气
        if chat_goal == "negotiation" and tone_analysis["aggressive"] > 0.3:
            if random.random() > 0.6:
                suggested_text = suggested_text.replace("你必须", "希望你能考虑")
                if "你必须" in text:
                    modification_points.append({
                        "type": "replacement",
                        "position": "middle",
                        "original": "你必须",
                        "suggested": "希望你能考虑",
                        "reason": "缓和命令式语气，更利于协商"
                    })
                    explanation += "将命令式语气改为请求式，更容易被接受。"
        
        # 如果情感分析显示过于消极，增加积极表达
        if emotion_analysis["negative"] > 0.6 and chat_goal != "emotional_support":
            if random.random() > 0.5:
                suggested_text = f"尽管存在一些挑战，但我相信我们能够解决。{suggested_text}"
                modification_points.append({
                    "type": "addition",
                    "position": "start",
                    "original": "",
                    "suggested": "尽管存在一些挑战，但我相信我们能够解决。",
                    "reason": "增加积极表达，平衡消极情绪"
                })
                explanation += "添加积极乐观的表达，平衡原文的消极情绪。"
        
        # 如果没有做任何修改，添加一个小的建议
        if suggested_text == text:
            if len(text) > 20:
                suggested_text = text.replace("。", "。我很期待您的反馈。", 1)
                modification_points.append({
                    "type": "addition",
                    "position": "middle",
                    "original": "。",
                    "suggested": "。我很期待您的反馈。",
                    "reason": "增加互动性表达，促进对话继续"
                })
                explanation = "添加互动性表达，鼓励对方回应。"
            else:
                suggested_text = f"{text} 期待您的想法。"
                modification_points.append({
                    "type": "addition",
                    "position": "end",
                    "original": "",
                    "suggested": " 期待您的想法。",
                    "reason": "增加开放性表达，促进对话"
                })
                explanation = "添加开放性表达，鼓励对话继续。"
        
        # 预期效果评估
        expected_effect = {
            "clarity": random.uniform(0.6, 0.9),
            "politeness": random.uniform(0.7, 0.95) if relationship_type in ["superior", "client"] else random.uniform(0.5, 0.8),
            "effectiveness": random.uniform(0.65, 0.85),
            "emotional_impact": random.uniform(0.6, 0.9)
        }
        
        return {
            "original_text": text,
            "suggested_text": suggested_text,
            "explanation": explanation,
            "modification_points": modification_points,
            "expected_effect": expected_effect,
            "confidence": random.uniform(0.7, 0.95)
        }


# 创建单例实例
virtual_nlp_model = VirtualNLPModel()